package com.qm.console.config.aspect;

import com.qm.console.model.SysOperationLog;
import com.qm.console.model.UserInfo;
import com.qm.console.service.SysOperationLogService;
import com.qm.console.component.util.DateUtil;
import com.qm.console.component.util.DateUtil;
import com.qm.console.model.SysOperationLog;
import com.qm.console.model.UserInfo;
import com.qm.console.service.SysOperationLogService;

import org.apache.shiro.subject.SimplePrincipalCollection;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

import lombok.extern.slf4j.Slf4j;

import static com.qm.console.utils.EmojiConverterUtil.emojiConvert;

/**
 * Created by Edison.hu on 18/9/7.
 */

@Aspect
@Component("WebLogAspect")
@Slf4j
public class WebLogAspect {


    @Autowired
    SysOperationLogService sysOperationLogService;

    @Autowired
    DateUtil dateUtil;


    @Pointcut("execution(public * com.qm.console.controller.rest..*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String httpMethod = request.getMethod();

        if(httpMethod.equals("GET"))
            return;

        // 记录下非get请求内容
        Integer uid = null;
        String username = null;
        HttpSession rs = request.getSession();
        SimplePrincipalCollection userinfo = (SimplePrincipalCollection) rs.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
        if (userinfo != null) {
            UserInfo u = (UserInfo) userinfo.getPrimaryPrincipal();
            username = u.getUsername();
            uid = u.getUid();
        }

        String url = request.getRequestURL().toString();
        String ip = request.getHeader("X-Forwarded-For");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String classMethod = joinPoint.getSignature().getDeclaringTypeName();
        String args = Arrays.toString(joinPoint.getArgs());
        SysOperationLog log = new SysOperationLog();
        log.setUid(uid);
        log.setUsername(username);

     //   sysOperationLogService.AddNewLog(uid,username,url,ip,args,httpMethod,classMethod,dateUtil.getCurrentTime());
        log.setUrl(url);
        log.setUserIp(ip);
        log.setArgs(emojiConvert(args));
        log.setHttpMethod(httpMethod);
        log.setClassMethod(classMethod);
        log.setVisitTime(dateUtil.getCurrentTime());
        sysOperationLogService.AddNewLog(log);
    }

//    @Around("webLog()")
//    public Object arround(ProceedingJoinPoint pjp) {
//        logger.info("方法环绕start.....");
//        try {
//            Object o =  pjp.proceed();
//
//            logger.info("方法环绕proceed，结果是 :" + o);
//            return o;
//        } catch (Throwable e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
//
//    @AfterReturning(returning = "ret", pointcut = "webLog()")
//    public void doAfterReturning(JSONObject ret) throws Throwable {
//        // 处理完请求，返回内容
//        logger.info("RESPONSE : " + ret);
//    }
}
